package com.hotelsystem.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hotelsystem.pojo.Employee;
import com.hotelsystem.pojo.Role;
import com.hotelsystem.service.EmployeeService;
import com.hotelsystem.service.RoleService;
import com.hotelsystem.util.ConstantValue;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Resource(name = "employeeServiceImpl")
    private EmployeeService employeeService;

    @Resource(name = "roleServiceImpl")
    private RoleService roleService;

    @RequestMapping("/toEmployee")
    public String toEmployeeInfo(Employee employee, Integer pageNum, Model model,Integer roleId){
            try {
                //设置当前页和每页数量
                PageHelper.startPage(pageNum,5);
                //设置查询条件
                if (roleId != null)
                    employee.getRole().setRoleId(roleId);
                List<Employee> employees = employeeService.getAllEmployeeByEmployee(employee);
                //获取PageInfo对象，该对象封装的分页的相关信息
                PageInfo<Employee> pageInfo = new PageInfo<>(employees);
                //查询分页
                model.addAttribute("pageInfo",pageInfo);
                //显示列表值
                List<Role> roles = roleService.getAllRoleInfo();
                model.addAttribute("roles",roles);
                //数据回显
                model.addAttribute("employee",employee);
            } catch (Exception e) {
                e.printStackTrace();
            }
        return "system/employee/employeeInfo";
    }

    @ResponseBody
    @RequestMapping("/deleteEmpByName")
    public Object deleteEmpByEmpName(String empName){
        Map<String,Object> maps = new HashMap<>();
        try {
            employeeService.deleteEmpInfoByName(empName);
            maps.put("success","true");
        } catch (Exception e) {
            maps.put("success","false");
            e.printStackTrace();
        }
        return maps;
    }

    @ResponseBody
    @RequestMapping("/addEmpByEmp")
    public Object addEmpByEmp(Employee employee,String imgBase64,HttpSession session){
        Map<String,Object> maps = new HashMap<>();
        try {
            //获得当前登录的creator
            Employee employee1 = (Employee) session.getAttribute(ConstantValue.LOGIN_USER);
            employee.setCreator(employee1.getUsername());
            employeeService.addEmpInfo(employee,imgBase64);
            maps.put("success",true);
        } catch (Exception e) {
            maps.put("success",false);
            e.printStackTrace();
        }
        return maps;
    }
    @ResponseBody
    @RequestMapping("/updateEmpByEmp")
    public Object updateEmpByEmp(Employee employee,String imgBase64,HttpSession session){
        Map<String,Object> maps = new HashMap<>();
        //获得当前登录的creator
        Employee employee1 = (Employee) session.getAttribute(ConstantValue.LOGIN_USER);
        employee.setCreator(employee1.getUsername());
        try {
            employeeService.updateEmpInfoByName(employee,imgBase64);
            maps.put("success",true);
        } catch (Exception e) {
            maps.put("success",false);
            e.printStackTrace();
        }
        return maps;
    }

    @ResponseBody
    @RequestMapping("/selectEmpByName")
    public Object selectEmpByName(String username){
        try {
            return employeeService.getEmpInfoByuserName(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 登录逻辑处理
     * @param username
     * @param password
     * @param session
     * @return
     */
    @PostMapping(value = "/emp_login")
    public String login(String username, String password, HttpSession session,Model model){
        /**
         * 编写shiro认证操作
         *
         */
        //1.获取subject
        // 1、获取Subject实例对象
       Subject subject = SecurityUtils.getSubject();
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //3.执行登录方法
        try {

            subject.login(token); 
            Employee employee = null;
            try {
                employee = employeeService.login(username);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String phone = employee.getPhone();
            String newPhone = phone.substring(0,3)+"-"+phone.substring(3,7)+"-"+phone.substring(7,11);
            employee.setPhone(newPhone);
            session.setAttribute(ConstantValue.LOGIN_USER,employee);
            if(employee.getStatus()==0){
                model.addAttribute("msg","当前用户状态不可用");
                return "login";

            }else {
                return "redirect:/main.html";
            }

        } catch (UnknownAccountException e){
            //登录失败：用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            //登录失败：密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }

        //登录方法 邓
        /*Map<String,Object> map = new HashMap<String, Object>();
        try {
            Employee employee =  employeeService.login(username,password);
            if (employee != null && employee.getStatus() == 1){
                String phone = employee.getPhone();
                String newPhone = phone.substring(0,3)+"-"+phone.substring(3,7)+"-"+phone.substring(7,11);
                employee.setPhone(newPhone);
                session.setAttribute(ConstantValue.LOGIN_USER,employee);
                map.put("success",true);
            } else {
                map.put("success",false);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;*/
    }
    //去到修改密码页面
    @RequestMapping("/toPassword")
    public String toPassword(){
        return "system/change/updatePassword";

    }
    /**
     * 修改密码
     * @param empId
     * @param newPassword
     * @param model
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/updatePassword")
    public Map<String, Object> updatePassword(Integer empId, String newPassword, Model model, HttpSession session) {
        Map<String,Object> map = new HashMap<String, Object>();
        try {
            Employee employee = (Employee) session.getAttribute(ConstantValue.LOGIN_USER);
            if (employee != null) {
                employeeService.update(empId, newPassword);
                map.put("success", true);
            } else {
                map.put("success", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 不存在返回true,存在返回false
     * @param username
     * @return
     */
    @ResponseBody
    @RequestMapping("/getValidateName")
    public Object getJsonByEmp(String username){
        try {
            Employee employee = employeeService.getEmpInfoByuserName(username);
            if (employee == null){
                return true;
            }else{
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    @RequestMapping("/getEmpInfoByName")
    public String getEmpInfoByName(String username,Model model){
        try {
            Employee employee = employeeService.getEmpInfoByuserName(username);
            model.addAttribute("emp",employee);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "system/employee/Employee";
    }

    /*@RequestMapping("/exit")
    public String exitHost(HttpSession session){
        //System.out.println(session);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        //退出shiro
       *//* Subject subject = SecurityUtils.getSubject();
        subject.logout();
        //清除会话
        if (session != null){
            session.invalidate();
        }*//*
        return "/login";
    }*/
}
